package com.tzpay.tzpay.presenter;

import android.content.Context;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.tzpay.tzpay.R;
import com.tzpay.tzpay.api.TzLoginRequest;
import com.tzpay.tzpay.api.TzLoginResponse;
import com.tzpay.tzpay.api.service.TzService;
import com.tzpay.tzpay.bean.UserInfo;
import com.tzpay.tzpay.common.BaseCallBack;
import com.tzpay.tzpay.common.ConstValue;
import com.tzpay.tzpay.utils.SPUtil;
import com.tzpay.tzpay.utils.SecurityUtil;
import com.tzpay.tzpay.utils.T;
import com.tzpay.tzpay.utils.TzCryptTool;

import java.text.SimpleDateFormat;

import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit2Instance;

public class LoginPresenter implements Presenter {
    private static final java.lang.String TAG = "LoginPresenter";
    private LoginLogicView logicView;
    private SPUtil spUtil;
    private Context mContext;
    private LoginLogicView.LoginListener loginListener;

    private TzService service;

    private SimpleDateFormat dateFormat = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss");

    private boolean isOnDestory = false;

    public LoginPresenter(LoginLogicView loginView) {
        this.spUtil = SPUtil.getInstance(loginView.getContext());
        mContext = loginView.getContext();
        this.logicView = loginView;
    }

    public LoginLogicView.LoginListener getLoginListener() {
        return loginListener;
    }

    public void setLoginListener(LoginLogicView.LoginListener loginListener) {
        this.loginListener = loginListener;
    }

    public void setView(LoginLogicView loginView) {
        this.logicView = loginView;
    }

    /**
     * 初始化,将用户上次登录信息显示,如果用户上次登录勾选了自动登录checkBox,则自动进行登录验证
     */
    public void init() {
        String username = spUtil.getString(ConstValue.Sp.USERNAME, "");
        String encodePass = spUtil.getString(ConstValue.Sp.PASSWORD, "");
        String password = SecurityUtil.decodeBase64(encodePass);
        boolean isRememberPass;

        if (spUtil.getBoolean(ConstValue.Sp.REMENBER_PASS_CHECKED, true)) {
            isRememberPass = true;
        } else {
            isRememberPass = false;
        }
        logicView.renderLasLoginUserInfo(username, password, isRememberPass);

        if (hasLoginForm(username, password)) {
            login(username, password, isRememberPass);
        }
    }

    /**
     * 登录方法
     *
     * @param username       用户名
     * @param password       密码
     * @param isRememberPass 是否勾选自动登录
     */
    public void login(final String username, final String password, boolean isRememberPass) {
        logicView.showProgress();
        if (TextUtils.isEmpty(username)) {
            logicView.setUsernameError();
            return;
        }
        if (TextUtils.isEmpty(password)) {
            logicView.setPasswordError();
            return;
        }
        if (service == null) {
            service = Retrofit2Instance.createRetrofit(TzService.TzBaseUrl).create(TzService.class);
        }
        TzLoginRequest request = new TzLoginRequest();
        request.setDeviceId(ConstValue.DEVICE_ID);
        request.setUserId(username);
        request.setUserPwd(password);
        request.setDeviceTime(dateFormat.format(System.currentTimeMillis()));
        request.setMac(TzCryptTool.md5ForLogin(request.getDeviceId(), request.getUserId(), request.getUserPwd()));

        Call<TzLoginResponse> login = service.login(request);

        LoginCallBack callBack = new LoginCallBack(LoginPresenter.this);
        callBack.setRememberPass(isRememberPass);
        callBack.setRequest(request);
        login.enqueue(callBack);

        // TODO test
//        handleLoginSuccess(username, password, isRememberPass, null);
    }

    private void handleLoginSuccess(String userName, String password, boolean isRemenberPass, TzLoginResponse response) {
        spUtil.save(ConstValue.Sp.USERNAME, userName);
        if (isRemenberPass) {
            String encodePasswd = SecurityUtil.encodeBase64(password);
            spUtil.save(ConstValue.Sp.PASSWORD, encodePasswd);
        } else {
            spUtil.save(ConstValue.Sp.PASSWORD, "");
        }
        saveIsRememberPass(isRemenberPass);
//        String responseStr = "{\"resMsg\":0,\"appShopInfo\":{\"shopId\":\"000000001\",\"orgName\":\"test\",\"shopName\":\"test1\",\"shopTel\":\"123\",\"shopAddr\":\"testaddr\",\"shopLogo\":null,\"orgKey\":\"2016040208568192\"},\"appShopFunction\":[{\"funcId\":\"00000000\",\"funcName\":\"翼支付\",\"merchantId\":\"01440109025345000\",\"param1\":\"01440109025374000\",\"param2\":\"05\",\"param3\":\"0001\",\"param4\":\"http://www.baidu.com\",\"param5\":\"55\",\"param6\":\"66\",\"param7\":\"453383\",\"param8\":\"23CB477D755315A3AE8D5E5559A41CAD93D85C807D295351\",\"param9\":\"88\",\"param10\":\"10\",\"funcType\":0},{\"funcId\":\"00000001\",\"funcName\":\"支付宝\",\"merchantId\":\"222222\",\"param1\":\"11\",\"param2\":\"11\",\"param3\":\"11\",\"param4\":\"11\",\"param5\":\"11\",\"param6\":null,\"param7\":null,\"param8\":null,\"param9\":null,\"param10\":null,\"funcType\":0}]}\n";
//        response = new Gson().fromJson(responseStr, TzLoginResponse.class);
        T.e(TAG, "---------> " + response.toString());

        UserInfo userInfo = UserInfo.getInstance();
        userInfo.setUserName(userName);
        userInfo.setPassword(password);
        userInfo.setResponse(response);

        if (isOnDestory) {
            return;
        }
        logicView.onSuccess(null);
        if (loginListener != null) {
            loginListener.goMainActivity();
        }
    }


    private void handleLoginFail(String resperr) {
        if (isOnDestory) {
            return;
        }
        logicView.onFailed(resperr);
    }


    /**
     * 是否含有用户信息
     */
    private boolean hasLoginForm(String username, String password) {
        return !TextUtils.isEmpty(username) && !TextUtils.isEmpty(password);
    }

    /**
     * 保存用户勾选记住密码选项
     *
     * @param isCheck
     */
    public void saveIsRememberPass(boolean isCheck) {
        spUtil.save(ConstValue.Sp.REMENBER_PASS_CHECKED, isCheck);
    }

    @Override
    public void onDestory() {
        isOnDestory = true;
    }


    /**
     * 登录回调
     */
    private static final class LoginCallBack extends BaseCallBack<LoginPresenter, TzLoginResponse> {

        private boolean isRememberPass;

        private TzLoginRequest request;

        public LoginCallBack(LoginPresenter presenter) {
            super(presenter);
        }

        public void setRememberPass(boolean rememberPass) {
            isRememberPass = rememberPass;
        }

        public TzLoginRequest getRequest() {
            return request;
        }

        public void setRequest(TzLoginRequest request) {
            this.request = request;
        }

        @Override
        public void onResponseEx(LoginPresenter presenter, Call<TzLoginResponse> call, Response<TzLoginResponse> response) {
            if (response == null || response.body() == null) {
                presenter.handleLoginFail(presenter.mContext.getString(R.string.text_no_network));
                return;
            }
            TzLoginResponse body = response.body();
            if (!body.isSuccess()) {
                presenter.handleLoginFail(body.getErrorMessage());
                return;
            }
            presenter.handleLoginSuccess(request.getUserId(), request.getUserPwd(), isRememberPass, body);
        }

        @Override
        public void onFailureEx(LoginPresenter presenter, Call<TzLoginResponse> call, Throwable throwable) {
            presenter.handleLoginFail(presenter.mContext.getString(R.string.text_no_network));
        }
    }

}
